import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/custom/real_rich_text.dart';
import 'package:flutter_juwo/ui/model/member_entity.dart';
import 'package:flutter_juwo/ui/model/upvip_entity.dart';
import 'package:flutter_juwo/ui/pages/homePages/serviceDialog.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/memberPage/tab_navigater.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';

import 'new_control.dart';

///会员中心页面
class MemberPage extends StatefulWidget {
  final String money;

  MemberPage(this.money);

  @override
  _MemberPageState createState() => _MemberPageState();
}

class _MemberPageState extends State<MemberPage> {
  MyPageState ps = MyPageState.LOADING;
  MemberEntity entity = null;
  MarketTab _currenttab = thisTabs[0];

  ///用户余额是否大于 298
  bool isBig = false;

  ///0 普通用户 1  vip
  String VIP = "1";

  void _selectTab(MarketTab tab) {
    setState(() {
      _currenttab = tab;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    double _money = double.parse(widget.money);
    isBig = _money >= 298.00;
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: UiUtils.appBar(context, "会员中心"),
      body: this.getBody(),
    );
  }

  Future getData() {
    DioManager.getInstance().get(Api.USER_RESPECT, null, (json) {
      entity = MemberEntity.fromJson(json);
      if (null == entity || null == entity.data) {
        ToastUtil.showShortToast(Api.ERR_NOTHING);
        Application.router.pop(context);
        return;
      }

      if (entity.code == Api.SUCCESS_CODE) {
        ps = MyPageState.HAVE_DATA;
        setState(() {});
        return;
      }

      if (entity.code == Api.ERROR_CODE) {
        ToastUtil.showShortToast(entity.message);
        Application.router.pop(context);
        return;
      }
    }, (err) {
      ToastUtil.showShortToast(err);
    });
  }

  getBody() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      return this.getContent();
    }
  }

  getContent() {
    List<Widget> list = [];
    list.add(this.getTop());
    list.add(this.getMiddle());
    list.add(this.getVipMsg());
    if (entity.data.type != VIP) {
      list.add(UiUtils.divider(height: 10));
      list.add(this.getBottom());
    }

    return Column(
      children: <Widget>[
        UiUtils.divider(),
        Expanded(
          flex: 1,
          child: ListView(
            children: list,
          ),
        )
      ],
    );
  }

  Widget row2() {
    return NewMarketingTabNavigation(
      currentTab: _currenttab,
      onSelectTab: _selectTab,
    );
  }

  Widget row3() {
    return Stack(
      children: thisTabs.map((item) {
        return Offstage(
          offstage: _currenttab != item,
          child: NewControl(
              pageKey: PageStorageKey<MarketTab>(item),
              type: item.tab,
              data: _currenttab.tab == "vip"
                  ? entity.data.vipList[1]
                  : entity.data.vipList[0]),
        );
      }).toList(),
    );
  }

  getTop() {
    List<Widget> list = [];
    list.add(this.getMemberType());
    list.add(this.getHead());
    if (entity.data.type != VIP) {
      list.add(this.getUpVip());
    }

    return Container(
      height: ScreenUtil().setWidth(382),
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(0)),
      decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage(Utils.getImgPath(
                  entity.data.type != VIP ? "top_banner_0" : "top_banner_2")),
              fit: BoxFit.fill)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: list,
      ),
    );
  }

  ///会员类型 普通会员  vip会员
  Widget getMemberType() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          0, ScreenUtil().setWidth(50), ScreenUtil().setWidth(14), 0),
      alignment: Alignment.centerRight,
      child: Container(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(20),
            ScreenUtil().setWidth(5),
            ScreenUtil().setWidth(10),
            ScreenUtil().setWidth(5)),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(18), bottomLeft: Radius.circular(18)),
          gradient: entity.data.type == VIP
              ? LinearGradient(colors: <Color>[
                  Color(0xFFb79f6f),
                  Color(0xFFa4834c),
                ])
              : LinearGradient(colors: <Color>[
                  Color(0xFFc7c7c7),
                  Color(0xFF8b8b8b),
                ]),
        ),
        child: Text(
          "${entity.data.name}",
          style:
              TextStyles.custom(28, Colors.white, Font.PingFangMedium),
        ),
      ),
    );
  }

  ///头像
  Widget getHead() {
    return Container(
      margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
      child: Row(
        children: <Widget>[
          Container(
            height: ScreenUtil().setWidth(120),
            width: ScreenUtil().setWidth(120),
            child: ClipOval(
              child: entity.data.pic != null
                  ? UiUtils.cachedNetworkImage(90, 90, entity.data.pic)
                  : Image.asset(Utils.getImgPath('icon_default_head')),
            ),
          ),
          Container(
            height: ScreenUtil().setWidth(120),
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  child: Text(
                    "${entity.data.tel}",
                    style: TextStyles.custom(
                        34, Colors.white, Font.PingFangBlod),
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  child: Text(
                    "会员有效期:${entity.data.deadLine}",
                    style: TextStyles.custom(
                        26, Colors.white, Font.PingFangMedium),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget getUpVip() {
    return GestureDetector(
      onTap: () {
        this.showToUser();
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(30),
            ScreenUtil().setWidth(30),
            ScreenUtil().setWidth(0),
            ScreenUtil().setWidth(0)),
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(20),
            ScreenUtil().setWidth(10),
            ScreenUtil().setWidth(16),
            ScreenUtil().setWidth(10)),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            border: Border.all(
                color: Color(0xffb7a580), width: ScreenUtil().setWidth(1))),
        child: RealRichText([
          TextSpan(
            text: "升级会员",
            style: TextStyles.custom(
                28, Color(0xffb7a580), Font.PingFangMedium),
          ),
          TextSpan(
            text: "（￥298）",
            style: TextStyles.custom(
                24, Color(0xffb7a580), Font.PingFangMedium),
          ),
          ImageSpan(
            AssetImage(Utils.getImgPath("icon_right_01")),
            imageWidth: ScreenUtil().setWidth(32),
            imageHeight: ScreenUtil().setWidth(32),
          ),
        ])

        /* Text("升级会员",)*/,
      ),
    );
  }

  ///Vip会员特权
  getMiddle() {
    return Container(
      margin: EdgeInsets.only(
          top: ScreenUtil().setWidth(20), left: ScreenUtil().setWidth(30)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            child: Text(
              "VIP会员特权",
              style: TextStyles.custom(
                  32, Colours.appC1, Font.PingFangBlod),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  ///显示普通会员和vip会员的特权
  getVipMsg() {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
      padding: EdgeInsets.only(bottom: ScreenUtil().setWidth(20)),
      decoration: BoxDecoration(
          border:
              Border.all(color: Colours.c243, width: ScreenUtil().setWidth(1)),
          color: Colors.white),
      child: Column(
        children: <Widget>[
          row2(),
          row3(),
        ],
      ),
    );
  }

  getBottom() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
            child: Text(
              "VIP会员",
              style: TextStyles.custom(
                  32, Colours.appC1, Font.PingFangBlod),
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(750),
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(30), 0, ScreenUtil().setWidth(30), 0),
            padding: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(30),
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(0),
                ScreenUtil().setWidth(30)),
            decoration: BoxDecoration(
                color: Color(0xfffff7f1),
                borderRadius: BorderRadius.circular(6),
                border: Border.all(
                    color: Color(0xFFff5000), width: ScreenUtil().setWidth(2))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  child: Text(
                    "尊贵会员",
                    style: TextStyles.custom(
                        32, Colours.appC1, Font.PingFangBlod),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
                  child: Text(
                    "${entity.data.vipCardList}",
                    style: TextStyles.custom(
                        28, Colours.appC3, Font.PingFangMedium),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
                  child: RealRichText([
                    TextSpan(
                        text: "￥",
                        style: TextStyles.custom(
                            20, Colours.appC16, Font.PingFangMedium)),
                    TextSpan(
                        text: "298.00",
                        style: TextStyles.custom(
                            32, Colours.appC16, Font.PingFangBlod)),
                  ]),
                ),
                Container(
                  child: Text(
                    "注意:开通尊贵VIP会员时,若可用余额充足，将从账户可用余额中扣除，否则请联系客服充值并开通",
                    style: TextStyles.custom(
                        26, Colours.appC3, Font.PingFangMedium),
                  ),
                )
              ],
            ),
          ),
          GestureDetector(
            onTap: () {
              this.showToUser();
            },
            child: Container(
              alignment: Alignment.center,
              width: ScreenUtil().setWidth(750),
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(30),
                  ScreenUtil().setWidth(30),
                  ScreenUtil().setWidth(30),
                  ScreenUtil().setWidth(50)),
              padding: EdgeInsets.fromLTRB(
                  0, ScreenUtil().setWidth(20), 0, ScreenUtil().setWidth(20)),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(50),
                gradient: LinearGradient(colors: <Color>[
                  Color(0xFFe7c780),
                  Color(0xFFd9ac57),
                ]),
              ),
              child: Text(
                isBig ? "立即升级" : "可用余额不足，立即联系客服充值并开通",
                style: TextStyles.custom(
                    30, Colors.white, Font.PingFangMedium),
              ),
            ),
          )
        ],
      ),
    );
  }

  _generalAlertDialog() {
    return AlertDialog(
      title: Text(
        '确定继续升级会员？',
        style:
            TextStyles.custom(30, Colours.appC1, Font.PingFangMedium),
      ),
      content: Text(
        '继续升级将从 可用余额 中扣除298元',
        style:
            TextStyles.custom(26, Colours.appC2, Font.PingFangRegular),
      ),
      actions: <Widget>[
        FlatButton(
          child: Text('取消',
              style: TextStyles.custom(
                  28, Colours.appC3, Font.PingFangMedium)),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        FlatButton(
          child: Text(
            '确认',
            style: TextStyles.custom(
                28, Colors.blue, Font.PingFangMedium),
          ),
          onPressed: () {
            Navigator.of(context).pop();
            showDialog(
                context: context,
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return new LoadingDialog(
                    text: "正在开通…",
                  );
                });
            upVip();
          },
        ),
      ],
    );
  }

  Future upVip() {
    DioManager.getInstance().post(Api.UP_VIP, null, (json) {
      UpvipEntity entity = UpvipEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortToast(Api.ERR_NOTHING);
        Navigator.of(context).pop();
        return;
      }

      if (entity.code == Api.SUCCESS_CODE) {
        getData();
        ToastUtil.showShortToast(entity.message);
        Navigator.of(context).pop();
        return;
      }

      if (entity.code == Api.ERROR_CODE || entity.code == Api.ERROR_CODE_0) {
        ToastUtil.showShortToast(entity.message);
        Navigator.of(context).pop();
      }
    }, (err) {
      Navigator.of(context).pop();
      ToastUtil.showShortToast(entity.message);
    });
  }

  void showToUser() {
    if (isBig) {
      ///确认继续升级会员
      showDialog(context: context, builder: (_) => _generalAlertDialog());
    } else {
      ///弹出客服页面
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return ServiceDialog(
              SpUtil.getString(SpKeys.serviceStartTime),
              SpUtil.getString(SpKeys.serviceEndTime),
              SpUtil.getString(SpKeys.serviceWx),
              SpUtil.getString(SpKeys.serviceQRCpode),
              isHome: false,
            );
          });
    }
  }
}
